package com.weiaibenpao.demo.chislim.sport;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.Snackbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.bigkoo.pickerview.OptionsPickerView;
import com.jaeger.library.StatusBarUtil;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.bean.Points;
import com.weiaibenpao.demo.chislim.customs.WheelView;
import com.weiaibenpao.demo.chislim.util.PaintView;
import com.weiaibenpao.demo.chislim.util.ProgressDialog;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.weiaibenpao.demo.chislim.R.layout.item;

public class FavouritePicActivity extends Activity implements PoiSearch.OnPoiSearchListener {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.sportDis)
    EditText sportDis;
    @BindView(R.id.setSport)
    RelativeLayout setSport;
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.sportCity)
    EditText sportCity;
    @BindView(R.id.select)
    ImageView select;
    private PaintView iv;
    private Bitmap baseBitmap;
    //private Canvas canvas = new Canvas();
    private Canvas canvas;
    private Paint paint;

    private Button button;
    private String distance;
    private int disSelect;
    private List<Integer> disList=new ArrayList<>();

    public static ArrayList<PolylineOptions> latLongList;
    PolylineOptions polygonOptions;

    AMap aMap;
    ArrayList<Float> xlists, ylists;

    int position;//标记  0 室内  1  室外

    double cenLat = 39.90866;      //当前地图中心点
    double cenLong = 116.397486;
    float zoom = 15;             //缩放比例

    MyBroadcast myBroadcast;  //广播对象
    boolean flag = false;

    PoiSearch poiSearch; //城市检索
    PoiSearch.Query query;
    private MarkerOptions markerOptions;
    private PopupWindow popupWindow;

    public int s_x = 0;  //手指按下的起点x
    public int s_y = 0;  //手指按下的起点y

    int heigh_y;
    int width_x;
    LatLng latLng;
    ProgressDialog progress;

    boolean flagNum = false;

    public ArrayList screenList = new ArrayList();
    private Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favourite_pic);
        context=new WeakReference<Activity>(this).get();
        StatusBarUtil.setColor(this , getResources().getColor(R.color.ku_bg ) , 0);
        ButterKnife.bind(this);
        mapView.onCreate(savedInstanceState);         // 此方法必须重写
        Intent intent = getIntent();
        position = intent.getIntExtra("position", 0);

        button = (Button) findViewById(R.id.button1);

        progress = new ProgressDialog(this);
        //绘图
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        final int width = outMetrics.widthPixels;
        int height = outMetrics.heightPixels;

        this.iv = (PaintView) this.findViewById(R.id.iv); // 创建一张空白图片
        baseBitmap = Bitmap.createBitmap(width, height / 3, Bitmap.Config.ARGB_4444); // 创建一张画布
        //baseBitmap = Bitmap.createBitmap(width, 640, Bitmap.Config.ARGB_8888); // 创建一张画布
        canvas = new Canvas(baseBitmap);
        //canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);//绘制透明色  
        canvas.drawColor(Color.GRAY);// 画布背景为灰色
        paint = new Paint();  // 创建画笔 // 画笔颜色为红色
        paint.setColor(Color.RED); // 画笔颜色为红色
        paint.setStrokeWidth(15); // 宽度5个像素
        canvas.drawBitmap(baseBitmap,// 先将灰色背景画上
                new Matrix(), paint);
        iv.setGetDataListener(new PaintView.getData() {
            @Override
            public void getFirstData(float x, float y) {
                xlists = new ArrayList<Float>();
                ylists = new ArrayList<Float>();

                if(!flagNum){
                    s_x = (int) x;
                    s_y = (int) y;
                    if(latLng != null){
                        getStartLatLong(s_x,s_y,width_x/2,heigh_y/2,latLng);
                    }
                    flagNum = true;
                }
            }

            @Override
            public void getMoveData(float x, float y) {
                xlists.add(x);
                ylists.add(y);
            }

            @Override
            public void getUpData() {
                Points points = new Points(xlists,ylists);
                screenList.add(points);
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(screenList.size() < 1){
                    Snackbar.make(setSport, "请绘制想跑的图形", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                if (("").equals(sportDis.getText().toString().trim())) {
                    Snackbar.make(setSport, "请输入要跑的路程", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                if (Double.parseDouble(sportDis.getText().toString().trim())>50){
                    Snackbar.make(setSport, "跑步里程不能超过50公里", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                initThread();
            }
        });

        //选择距离，获得焦点是触发
//        sportDis.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                createBottomSheetDialog();
//                openPopWindow();
//
//            }
//        });

        initMap();

        //配置广播，接收当前是否有跑步正在进行中
        myBroadcast = new MyBroadcast();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.lijianbao.mapLocationLatLong");
        FavouritePicActivity.this.registerReceiver(myBroadcast, filter);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        heigh_y = iv.getHeight() ;           //-25
        width_x = iv.getWidth();             //-135
        Log.i("宽高",heigh_y + "------" + width_x);
    }

    /**
     * 城市检索
     * @param strCity
     */
    public void getCity(String strCity) {
        Log.e("中心点1", "onPoiSearched: ");

        //搜索位置
        query = new PoiSearch.Query(strCity, "", "");
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(1);//设置查询页码
        //构造 PoiSearch 对象，并设置监听。
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        //发送请求
        poiSearch.searchPOIAsyn();  //异步搜索
    }

    /**
     * 实例化地图
     */
    public void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        aMap.setTrafficEnabled(true);           // 显示实时交通状况
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 地图模式
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));

        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                cenLat = cameraPosition.target.latitude;
                cenLong = cameraPosition.target.longitude;
                zoom = cameraPosition.zoom;
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {

            }
        });
    }

    /*地图检索*/
    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        Log.e("wlx", "onPoiSearched: ");
//        List<String> strs = new ArrayList<String>();
//        List<LatLonPoint> latLonList = new ArrayList<LatLonPoint>();
        List<PoiItem> items = poiResult.getPois();

        if (items != null && items.size() > 0) {
           showPicker(items);

        }
    }

    /**
     * 显示poi检索
     */
    private void showPicker(final List<PoiItem> items) {
        OptionsPickerView optionsPickerView=new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int i, int i1, int i2, View view) {
                LatLonPoint point = items.get(i).getLatLonPoint();
                latLng = new LatLng(point.getLatitude(),point.getLongitude());

                if(s_x != 0 && s_y != 0){

                    Log.e("中心点1", "onPoiSearched: " + latLng.toString());
                    getStartLatLong(s_x,s_y,width_x/2,heigh_y/2,latLng);
                }else{
                    setIntro(latLng,10);
                }
            }
        })
                .setTitleText(" ")
                .setDividerColor(Color.BLACK)
                .setOutSideCancelable(true)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setSubmitColor(Color.parseColor("#333333"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#666666"))//取消按钮文字颜色
                .setLineSpacingMultiplier(2.0f)
                .build();
        optionsPickerView.setPicker(items);
        optionsPickerView.show();
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }
    /**
     * popwindow底部显示
     */
    public void openPopWindow() {
        View view = createBottomView();
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.white));
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
//        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindow.setOutsideTouchable(true);
        //设置可以点击
        popupWindow.setTouchable(true);

////        设置添加屏幕的背景透明度
        backgroundAlpha(0.8f);

        //设置划入动画
        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        //从底部显示
        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);

        //点击其他地方消失
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);

            }
        });
    }

    /**
     * 设置添加屏幕的背景透明度
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha){
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);

    }
    /**
     * 底部滑动显示
     *
     * @param page
     * @param num
     * @param n
     */
    private BottomSheetDialog mBottomSheetDialog;

    private void createBottomSheetDialog() {

        //new 一个BottomSheetDialog对象
        mBottomSheetDialog = new BottomSheetDialog(this);
        //获取要添加到BottomSheetDialog中的布局view
        View view = createBottomView();
        //将布局添加到BottomSheetDialog中
        mBottomSheetDialog.setContentView(view);
        //显示
        mBottomSheetDialog.show();
    }

    /**
     * @return
     */
    private View createBottomView() {

        distance="1km";
        disSelect=0;
        List<String> list = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            list.add(i + "km");
            disList.add(i);
        }
        View view = LayoutInflater.from(this).inflate(item, null, false);
        TextView cancel = (TextView) view.findViewById(R.id.cancel_interest);
        TextView commit = (TextView) view.findViewById(R.id.commit_interest);
        WheelView wheel = (WheelView) view.findViewById(R.id.wheel_in);
        wheel.setOffset(1);
        wheel.setItems(list);
        wheel.setOnWheelViewListener(new WheelView.OnWheelViewListener(){
            @Override
            public void onSelected(int selectedIndex, String item){
                super.onSelected(selectedIndex, item);
                distance=item;
                disSelect=selectedIndex;

            }

        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sportDis.setText(distance);
                popupWindow.dismiss();
            }
        });
        return view;
    }

    /**
     * 切换地图显示中心点
     */
    public void setIntro(LatLonPoint latLonPoint) {
        double mLatitude = latLonPoint.getLatitude();
        double mLongitude = latLonPoint.getLongitude();
        if (mLatitude != 0 && mLongitude != 0) {

            LatLng latLng = new LatLng(mLatitude, mLongitude);

            markerOptions = new MarkerOptions();

            markerOptions.position(latLng);
            markerOptions.visible(true);
            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_above));
            markerOptions.icon(bitmapDescriptor);

            aMap.addMarker(markerOptions);
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
        }
    }

    @OnClick({R.id.back, R.id.select})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.select:
                if(!"".equals(sportCity.getText().toString().trim())){
                    getCity(sportCity.getText().toString().trim());

                }else {
                    Snackbar.make(setSport, "请输入你想跑的地点", Snackbar.LENGTH_SHORT).show();
                }
                break;
        }
    }

    /**
     * 内部类实现进度条和界面动态显示
     */
    public class MyBroadcast extends BroadcastReceiver {

        public MyBroadcast() {

        }

        /**
         * @param context
         * @param intent  intent1.putExtra("state",num);
         */
        @Override
        public void onReceive(Context context, Intent intent) {

            String cor = intent.getStringExtra("contextActivity");        //当前正在跑跑步的activity
            int state = intent.getIntExtra("state", 0);
            //如果广播的跑步界面地址不为空，切跑步状态不为4，还没有跳转，则提示跳转
            if (cor != null && state != 4 && !flag) {
                flag = true;
                Intent intent1 = new Intent();
                intent1.setAction(cor);//设置intent的Action属性值
                intent1.addCategory(Intent.CATEGORY_DEFAULT);//不加这行也行，因为这个值默认就是Intent.CATEGORY_DEFAULT
                startActivity(intent1);
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mapView.onDestroy();
        unregisterReceiver(myBroadcast);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mapView.onSaveInstanceState(outState);
    }

    /**
     *
     * @param x  触点起点的x轴
     * @param y  触点起点的y轴
     * @param p_x    画布中心点x坐标
     * @param p_y    画布中心点y坐标
     * @param latLng   当前地图起点坐标
     */
    public void getStartLatLong(int x,int y,int p_x,int p_y,LatLng latLng){
        //将起点坐标转化为屏幕坐标
        Point point = getScreen(latLng);
        Log.i("中心点5",point.x + "----" + point.y);
        point = getScreen(latLng);
        Log.i("中心点6",point.x + "----" + point.y);
        Log.i("中心点2",latLng.toString());
        //计算当前触点相对于中心点的位置
        int x1 = x - p_x;
        int y1 = y - p_y;
        //计算接下来屏幕中点的所在屏幕位置
        int x2 = point.x - x1;
        int y2 = point.y - y1;
        //将接下来屏幕中点的所在屏幕位置转化为实际地球经纬度
        LatLng latLng1 = getLatLong(new Point(x2,y2));
        Log.i("中心点3",latLng1.toString());
        //设置中点
        setIntro(latLng1,17);
    }

    /**
     * 根据屏幕坐标值返回地球经纬度值
     */
    public LatLng getLatLong(Point point){
        return aMap.getProjection().fromScreenLocation(point);
    }

    /**
     * 根据地球经纬度值返回屏幕坐标值
     */
    public Point getScreen(LatLng latLng){
        return aMap.getProjection().toScreenLocation(latLng);
    }

    /**
     * 切换地图显示中心点
     */
    public void setIntro(LatLng latLng, float n) {
        //设置中心点和缩放比例
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
    }


    /**
     * 将所有屏幕坐标转化为地球经纬度
     */

    public void getLatlongPointList(){
        latLongList = new ArrayList();
        for(int i = 0;i < screenList.size();i++){
            int num = ((Points)screenList.get(i)).getX().size();
            polygonOptions = new PolylineOptions();
            for(int j = 0;j <num ;j++){
                polygonOptions.add(getLatLong(new Point(Math.round((float)((Points)screenList.get(i)).getX().get(j)), Math.round((float)((Points)screenList.get(i)).getY().get(j)))));
            }
            latLongList.add(polygonOptions);
        }
    }

    /**
     * 在线程中进行点位的转化
     */
    public void initThread(){
//        progress.showDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
          //      getLatlongList(xlists,ylists);
                getLatlongPointList();
                Message msg = new Message();
                msg.arg1 = 0;
                hander.sendMessage(msg);
            }
        }).start();
    }

    private Handler hander = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.arg1 == 0){
             //   Log.i("点数",latLongList.size()+"-------");
                progress.cancelDialog();
                goStartSport();
            }
        }
    };

    /**
     * 前往跑步
     */
    public void goStartSport(){
        if (position == 0) {
            Intent intent = new Intent(FavouritePicActivity.this, FavouritMapActivity.class);
            intent.putExtra("dis",  Double.parseDouble(sportDis.getText().toString())* 1000);
            intent.putExtra("cenLat", cenLat);
            intent.putExtra("cenLong", cenLong);
            intent.putExtra("zoom", zoom);
            startActivity(intent);
            finish();
        }
        if (position == 1) {
            Intent intent = new Intent(FavouritePicActivity.this, FavouriteMapOutHomeActivity.class);
            Log.e("ljb",disSelect+"----");
            intent.putExtra("dis", Double.parseDouble(sportDis.getText().toString())* 1000);
            intent.putExtra("cenLat", cenLat);
            intent.putExtra("cenLong", cenLong);
            intent.putExtra("zoom", zoom);
            startActivity(intent);
            finish();
        }
    }
}
